<script setup lang="ts">
  import { ref } from "vue"
  import { loginByUsername } from "@/apis/user"
  import type { InputOnBlurEvent } from "@uni-helper/uni-app-types/index"
  import { useUserStore } from "@/stores/user"
  const store = useUserStore()
  defineOptions({
    options: {
      styleIsolation: "shared",
    },
  })

  // 声明 mobile 提示文本 表单的ref
  // 传递类型 明确告诉  mobileRef，说你就是用来关联表单的， 一定存在！！
  const form = ref<UniHelper.UniFormsInstance>()
  // 声明 mobile 提示文本 表单的ref
  const mobileRef = ref<UniHelper.UniFormsItemInstance>()
  const passwordRef = ref<UniHelper.UniFormsItemInstance>()
  const isAgree = ref(false)

  // 定义表单数据对象
  const formdata = ref({
    mobile: "13230000011",
    password: "abc12345",
  })
  // 定义表单验证规则！！
  const formRules = {
    mobile: {
      rules: [
        { required: true, errorMessage: "请填写手机号码" },
        { pattern: "^[1][3-8][0-9]{9}$", errorMessage: "手机号码格式不正确" },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: "请输入密码" },
        { pattern: "^[a-zA-Z0-9]{8}$", errorMessage: "密码格式不正确" },
      ],
    },
  }

  const onSubmit = async () => {
    try {
      await form.value?.validate?.()
      if (!isAgree.value) {
        uni.showToast({ title: "您还没有勾选用户协议", icon: "none" })
        return
      }
      const res = await loginByUsername(formdata.value)
      // 存token
      store.setToken(res.token)

      uni.navigateBack()
    } catch (error) {
      console.log("不通过")
    }
  }
</script>

<template>
  <uni-forms class="login-form" ref="form" :model="formdata" :rules="formRules">
    <uni-forms-item name="mobile" ref="mobileRef">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
        v-model="formdata.mobile"
        @blur="(e:InputOnBlurEvent) => mobileRef?.onFieldChange?.(e.detail.value)"
      />
    </uni-forms-item>
    <uni-forms-item name="password" ref="passwordRef">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入密码"
        v-model="formdata.password"
        placeholder-style="color: #C3C3C5"
        @blur="(e:InputOnBlurEvent) => passwordRef?.onFieldChange?.(e.detail.value)"
      />
    </uni-forms-item>

    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onSubmit">登 录</button>
  </uni-forms>
</template>
<style lang="scss">
  @import "styles.scss";
</style>
